//
//  KeyChain.m
//  KotnetAutologin
//
//	handle saving and getting passwords from keychain
//
//  Created by Kristof Marien on 3/01/10.
//  Copyright 2010 KotnetAutologin. All rights reserved.
//

#import "KeyChain.h"

static char *serviceName = "KotnetAutologin";

@implementation KeyChain
/**
 *  save a password
 */
- (void) savePassWordKeyChain:(NSString *) account :(NSString *) password;
{
	SecKeychainAddGenericPassword(nil, strlen(serviceName), serviceName, strlen((void *)[account UTF8String]), 
										   (void *)[account UTF8String], strlen((void *)[password UTF8String]), 
										   (void *)[password UTF8String], nil);
}
/**
 *  get a password
 */
- (NSString*) getPasswordKeyChain:(NSString *) account
{
	if ([account length] < 1)
		return @"not found PWD";
	void *passwordData = nil;
	SecKeychainItemRef itemRef = nil;
	UInt32 passwordLength;
	OSStatus status;
	status = SecKeychainFindGenericPassword(nil, strlen(serviceName), serviceName, 
											strlen((void *)[account UTF8String]), (void *)[account UTF8String], 
											&passwordLength, &passwordData, &itemRef);
	if (status == -25300) {
		return @"not found PWD";
	}
	SecKeychainItemFreeContent(nil, passwordData);
	return [[NSString stringWithUTF8String:passwordData] substringToIndex:passwordLength];
}
/**
 *  delete a password
 */
- (void) deletePasswordKeyChain:(NSString *) account
{
	SecKeychainItemRef itemRef = nil;
	
	SecKeychainFindGenericPassword(nil, strlen(serviceName), serviceName, strlen((void *)[account UTF8String]),
											(void *)[account UTF8String], nil, nil, &itemRef);
	
	SecKeychainItemDelete(itemRef);
}
@end
